/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelBiseccion.java
 *
 * Created on 11-oct-2010, 14:12:47
 */
package interfaz.FuncionPanels;

//import java.awt.FlowLayout;
//import javax.print.DocFlavor.STRING;
//import javax.management.monitor.GaugeMonitor;
import java.awt.Color;
import java.util.Locale;
import javax.swing.JFrame;
//import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

//import javax.swing.table.TableModel;
import metodos.sistec.Dolytle;
import metodos.sistec.FactorizacionPivParcial;
import metodos.sistec.FactorizacionSimple;
import metodos.sistec.GaussSeidel;
import metodos.sistec.Gaussiana;
import metodos.sistec.GaussianaPivParcial;
import metodos.sistec.GaussianaPivTotal;
import metodos.sistec.GaussianaPivoteoParcial;
import metodos.sistec.Jacobi;
import metodos.sistec.MatrizBanda;
import org.jdesktop.swingx.JXTextField;
//import org.jdesktop.swingx.JXTable;




/**
 *
 * @author The NuMethod Team
 */
public class PanelMatriz extends javax.swing.JPanel {
    private static DefaultTableModel ma;
    private static DefaultTableModel mb;
    private static DefaultTableModel mx;
    /** Creates new form PanelBiseccion */
    public PanelMatriz() {
        ma = new DefaultTableModel();
        mb = new DefaultTableModel();
        mx = new DefaultTableModel();
        initComponents();
        initComponents2();
    }




    // <editor-fold defaultstate="collapsed" desc="Helpful getters">
        public static DefaultTableModel getMa() {
        return ma;
    }

    public static DefaultTableModel getMb() {
        return mb;
    }

    public static DefaultTableModel getMx() {
        return mx;
    }
    // </editor-fold>
    private void initComponents2() {
        //this.jTable1.setVisible(false);
        this.TableA.setEditable(true);
        TableA.setShowGrid(true);
        TableA.setOpaque(true);
        TableA.setAutoStartEditOnKeyStroke(true);
        TableA.setRolloverEnabled(true);
        TableA.setSurrendersFocusOnKeystroke(true);
        TableA.setTerminateEditOnFocusLost(true);
        TableA.setFillsViewportHeight(true);


        TableX.setEditable(false);
        TableX.getTableHeader().setVisible(false);
        TableX.setVisible(false);
//        TableA.setAutoResizeMode(JXTable.AUTO_RESIZE_LAST_COLUMN);
//        TableB.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);
//        TableX.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);
        TableA.setVisibleColumnCount(0);

        rebuildTableModels(3);

        
    }

    /**
     * Este metodo devuelve los valores existentes en las tablas a dos variables
     * <br>Pasadas como parametro.
     * 
     * <p>
     * WARNING: esta version hasta ahora no soporta variables distintas a numeros<br>
     * asi que se debe de tener cuidado de no ingresar ningun valor que no sea numerico en las tablas.
     * @param A
     * @param B
     */
    private void getDataFromTables(double[][] A, double[] B) {
        int rowCount = this.TableA.getModel().getRowCount();
        int columnCount = this.TableA.getModel().getColumnCount();
        // A = new double[rowCount][columnCount];
        //Obtener los datos desde el modelo de tabla actual
        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < columnCount; j++) {
                A[i][j] = Double.parseDouble(TableA.getModel().getValueAt(i, j).toString());
                System.out.print(Double.parseDouble(this.TableA.getModel().getValueAt(i, j).toString()) + " ");
            }
            System.out.println("");
        }

        //Obtener los datos desde la tabla B
        //B = new double[rowCount];
        for (int i = 0; i < B.length; i++) {
            B[i] = Double.parseDouble(TableB.getModel().getValueAt(i, 0).toString());
        }

    }

    /**
     * Este metodo coloca datos tipo Double en la tabla X.
     * <br>WARNING: este metodo depende estrictamente de sus valores, cualquier intento de
     * <br>utilizar este metodo con unos datos extraños terminara en error
     * @param X los datos a poner en la tablaX
     */
    private void setDataToTableX(double[] X) {
        Double[] aX = new Double[X.length];
        int n = X.length;
        //La tabla solo recibe objetos tipo Double con "D" mayuscula, el tipo basico double con "d" minuscula no es un Object.
        for (int i = 0; i < n; i++) {
            aX[i] = new Double(X[i]);
        }

        DefaultTableModel t = (DefaultTableModel) TableX.getModel();

        for (int i = 0; i < n; i++) {
            t.setValueAt(aX[i], 0, i);
        }

        //Actualizar los datos en la tabla
        t.fireTableDataChanged();

    }

    /**
     * Metodo que reconstruye de forma dinamica los modelos de tabla
     * luego de cada entrada de datos
     * @param a el numero de ecuaciones del sistema
     */
    private void rebuildTableModels (Integer a){
         //Constuir el modelo para la tabla A
            Double[][] test = new Double[a][a];
            String[] names = new String[a];

            for (int i = 0; i < a; i++) {
                String aTest = "X" + (i + 1);
                names[i] = aTest;
            }

            //Constuir el modelo para la tabla B
            Double[][] testB = new Double[a][1];
            String[] namesB = new String[1];

            for (int i = 0; i < 1; i++) {
                String aTest = "B" + (i + 1);
                namesB[i] = aTest;
            }

            //Construir el Modelo para la tabla X
            Double[][] testX = new Double[1][a];
            String[] namesX = new String[a];


            for (int i = 0; i < a; i++) {
                String aTest = "X" + (i + 1);
                namesX[i] = aTest;
            }

            //COnfigurar los modelos de tabla para las 3 tablas disponibles.
            ma = new DefaultTableModel(test, names);
            this.TableA.setModel(ma);

            mb = new DefaultTableModel(testB, namesB);
            this.TableB.setModel(mb);

            mx = new DefaultTableModel(testX, namesX);
            TableX.setModel(mx);

            ma.fireTableDataChanged();
            mb.fireTableDataChanged();
            mx.fireTableDataChanged();
            //TableA.repaint();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TableA = new org.jdesktop.swingx.JXTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        TableB = new org.jdesktop.swingx.JXTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        TableX = new org.jdesktop.swingx.JXTable();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        FieldMatriz2 = new javax.swing.JTextField();
        LabelStatus = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        setToolTipText("Sistemas de Ecuaciones Lineales");

        TableA.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(TableA);

        TableB.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null},
                {null}
            },
            new String [] {
                "Title 1"
            }
        ));
        jScrollPane2.setViewportView(TableB);

        TableX.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(TableX);

        jLabel4.setText("Matriz A");

        jLabel5.setText("Vector B");

        jLabel6.setText("Vector X");

        FieldMatriz2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                FieldMatriz2MouseClicked(evt);
            }
        });
        FieldMatriz2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FieldMatriz2ActionPerformed(evt);
            }
        });

        LabelStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        LabelStatus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/Icons16/idea.png"))); // NOI18N
        LabelStatus.setText("Inserta el # de ecuaciones a solucionar");
        LabelStatus.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(FieldMatriz2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(LabelStatus))
                    .addComponent(jLabel6)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel4)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 510, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel5)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FieldMatriz2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(LabelStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addGap(1, 1, 1)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(228, 228, 228))
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Metodo que extrae de los textfield`s los valores de los parametros
     * para los metodos iterativos.
     */
    private void FieldMatriz2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FieldMatriz2ActionPerformed
        try {
            Integer a = Integer.parseInt(this.FieldMatriz2.getText());
            if (a > 1) {
                rebuildTableModels(a);
            } else {
                LabelStatus.setText("Esta aplicacion soluciona sistemas de mas de una ecuacion, por favor intenta nuevamente");
            }
        } catch (NumberFormatException numberFormatException) {
            LabelStatus.setText("Imposible parsear numero, intenta otra vez");
        }
    }//GEN-LAST:event_FieldMatriz2ActionPerformed

    private void FieldMatriz2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_FieldMatriz2MouseClicked
        LabelStatus.setText("Inserta el # de ecuaciones a parsear");
    }//GEN-LAST:event_FieldMatriz2MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField FieldMatriz2;
    private javax.swing.JLabel LabelStatus;
    private org.jdesktop.swingx.JXTable TableA;
    private org.jdesktop.swingx.JXTable TableB;
    private org.jdesktop.swingx.JXTable TableX;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    // End of variables declaration//GEN-END:variables

    public static void main(String[] args) {
        JFrame myFrame = new JFrame("Test");
        PanelMatriz m = new PanelMatriz();
        //myFrame.setLayout(new FlowLayout());
        myFrame.add(m);

        myFrame.pack();
        myFrame.setVisible(true);


    }
}
